package com.siwei.mes.service.erp.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.ConvertUtils;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.config.UidUtils;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.dto.ExperimentDetailDto;
import com.siwei.mes.entity.dto.RwdextraExtendUpdateDto;
import com.siwei.mes.entity.erp.*;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.ExperimentGenConfig;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKyqd;
import com.siwei.mes.entity.mixproportion.MixProportion;
import com.siwei.mes.entity.mixproportion.MixProportionReport;
import com.siwei.mes.entity.mixproportion.MixProportionVerifyRecord;
import com.siwei.mes.entity.sync.erp.ErpProject;
import com.siwei.mes.entity.system.SystemParam;
import com.siwei.mes.entity.vo.ExperimentPrintVo;
import com.siwei.mes.enums.*;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.erp.RwdextraExtendMapper;
import com.siwei.mes.mapper.erp.RwdextraMapper;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.experiment.ExperimentGenConfigMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.mixProportion.MixProportionMapper;
import com.siwei.mes.mapper.mixProportion.MixProportionVerifyRecordMapper;
import com.siwei.mes.mapper.syncErp.ErpProjectMapper;
import com.siwei.mes.mapper.system.SignatureMapper;
import com.siwei.mes.mapper.system.SystemParamMapper;
import com.siwei.mes.service.erp.*;
import com.siwei.mes.service.experiment.OpenAppraisalService;
import com.siwei.mes.sync.erp.entity.GenConcreteResult;
import com.siwei.mes.sync.erp.entity.ItemorderFinish;
import com.siwei.mes.upload.erp.entity.ErpAddTaskPhbLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * ERP任务单扩展信息 （品控）(RwdextraExtend)表服务实现类
 *
 * @author linzi
 * @since 2024-08-02 16:22:23
 */
@Slf4j
@Service
public class RwdextraExtendServiceImpl implements RwdextraExtendService {
    @Resource
    private RwdextraExtendMapper rwdextraExtendMapper;
    @Resource
    private RwdextraExtendUpdateLogService rwdextraExtendUpdateLogService;
    @Resource
    private RwdextraUpdateLogService rwdextraUpdateLogService;
    @Resource
    private MixProportionMapper mixProportionMapper;
    @Resource
    private MixProportionVerifyRecordMapper mixProportionVerifyRecordMapper;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;
    @Resource
    private ErpProjectMapper erpProjectMapper;
    @Resource
    private OpenAppraisalService openAppraisalService;
    @Resource
    private RwdextraService rwdextraService;
    @Resource
    private RwdextraMapper rwdextraMapper;
    @Resource
    private ExperimentGenConfigMapper experimentGenConfigMapper;
    @Resource
    private RwdextraExtendService rwdextraExtendService;
    @Resource
    private PhbhistoryService phbhistoryService;
    @Resource
    private SystemParamMapper systemParamMapper;
    @Resource
    private SignatureMapper signatureMapper;

    private String KY_TEST_PROJECT_CODE = TestProjectEnum.CONCRETE_PARAM_KYQD.getCode();
    private String KS_TEST_PROJECT_CODE = TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode();
    private String LLZHL_TEST_PROJECT_CODE = TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode();
    private String KZ_TEST_PROJECT_CODE = TestProjectEnum.CONCRETE_PARAM_KZQD.getCode();


    @Override
    public void hasItemorder(Rwdextra rwdextra, String qualityCertificateNo) {
        if (rwdextra == null) {
            log.info("hasItemorder...任务单对象为空");
            return;
        }
        RwdextraExtend entity = rwdextra.getRwdextraExtend();
        entity.setUpdateTime(new Date());
        entity.setIsHasItemorder(1);
        entity.setSupplyStartTime(new Date());
        entity.setSupplyEndTime(new Date());
        entity.setMixProportionNo(UidUtils.genNoNumberByYear(GenerateCodeEnum.MIX_PROPORTION.getCode(), "%05d"));
        entity.setQualityCertificateNo(qualityCertificateNo);
        RwdextraInfo rwdextraInfo = rwdextra.getRwdextraInfo();
        log.info("给任务单打印json赋值【第一车】 配合比编号:【{}】", rwdextraInfo.getFPhbNo());
        MixProportion mixProportion = mixProportionMapper.selectByPhbNo(rwdextraInfo.getFPhbNo());
        setMixProportionPktzId(mixProportion, rwdextra);
        rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void setRwdextraPrintInfo(RwdextraPrintEntity rwdextraPrintEntity) {
        Rwdextra rwdextra = rwdextraPrintEntity.getRwdextra();
        if (rwdextra == null) {
            log.info("setRwdextraPrintInfo...任务单对象为空");
            return;
        }
        GenConcreteResult genConcreteResult = rwdextraPrintEntity.getGenConcreteResult();
        ItemorderFinish itemorderFinish = rwdextraPrintEntity.getItemorderFinish();
        RwdextraExtend entity = rwdextra.getRwdextraExtend();
        MixProportion mixProportion = mixProportionMapper.selectByPhbNo(rwdextra.getRwdextraInfo().getFPhbNo());

        /**抗渗不管是第几车，都需要赋值一下，不管任务单传几次，都会是同一个抗渗委托编号，这个是不会变的*/
        log.info("给任务单打印json赋值【第一车】");
        RwdextraPrintInfo rwdextraPrintInfo = new RwdextraPrintInfo();
        if (entity.getPrintJson() != null) {
            rwdextraPrintInfo = JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
        }
        setRwdextraExtendPrintKs(rwdextra, rwdextraPrintInfo, genConcreteResult);
        if ("1".equals(rwdextraPrintEntity.getIsFirstCar())) {
            Integer frwd = rwdextra.getFrwdh();
            Phbhistory phbhistory = phbhistoryService.selectByRwdhAndTime(frwd, mixProportion, 0);
            rwdextraPrintInfo.setPhbhistory(phbhistory);
            entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
        }
        if (mixProportion != null) {
            //RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
            /**保存任务单扩展表对应打印信息**/
            //if (entity.getPrintJson() == null) {
            //    rwdextraPrintInfo = new RwdextraPrintInfo();
            //}
            setRwdextraExtendPrintKy(rwdextraPrintInfo, genConcreteResult);
            setRwdextraExtendPrintKz(rwdextraPrintInfo, genConcreteResult);
            setRwdextraExtendPrintKllz(rwdextraPrintInfo, genConcreteResult, rwdextra.getRwdextraInfo().getKllz());
            Integer frwd = rwdextra.getFrwdh();
            List<Phbhistory> phbhistoryList = rwdextraPrintInfo.getPhbhistoryList();
            /** 查询小于小票创建时间的调整记录*/
            Phbhistory phbhistory = phbhistoryService.selectByRwdhAndPhbOne(frwd, mixProportion, itemorderFinish.getITID(),itemorderFinish.getMixtable());
            if (rwdextraPrintInfo.getPhbhistoryList() == null) {
                phbhistoryList = new ArrayList();
            }
            /** 如果存在入已入库的调整记录，则不保存*/
            if (!phbhistoryList.stream().anyMatch(h -> h.getPhid() != null && h.getPhid().equals(phbhistory.getPhid()))) {
                phbhistoryList.add(phbhistory);
            }
            phbhistoryService.sortPhbhistoryList(phbhistoryList,mixProportion);
            rwdextraPrintInfo.setPhbhistoryList(phbhistoryList);
            entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
        }

        rwdextraExtendMapper.updateByPrimaryKeySelective(entity);

        rwdextra.setRwdextraExtend(entity);
        log.info("保存开盘鉴定表");
        openAppraisalService.hasOpenAppraisal(rwdextra, itemorderFinish, rwdextraPrintEntity.getIsUpdate());
    }

    @Override
    public void setRwdextraPrintInfoPhb(Rwdextra rwdextra) {
        try {
            RwdextraExtend entity = rwdextra.getRwdextraExtend();
            /**配合比信息**/
            MixProportion mixProportion = mixProportionMapper.selectByPhbNo(rwdextra.getPhbshow());
            if (mixProportion != null) {
                RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
                /**保存任务单扩展表对应打印信息**/
                if (entity.getPrintJson() == null) {
                    rwdextraPrintInfo = new RwdextraPrintInfo();
                }
                /**保存任务单扩展表对应打印信息**/
                setMixProportionPktzId(mixProportion, rwdextra);
                rwdextraPrintInfo.setMixProportionInfo(mixProportion);


                String kllzhl = ConvertUtils.getKllzhl(rwdextra.getRwdextraInfo().getKllz());

                rwdextraPrintInfo.setLlzhl(kllzhl);
                entity.setLlzHl(kllzhl);
                rwdextraPrintInfo.setSignature(signatureMapper.loadById(1L));

                entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
                rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
            }
        } catch (Exception e) {
            log.error("给任务单打印json赋值（配合比失败）,错误信息：【{}】", e.getMessage(), e);
        }
    }

    @Override
    public void updateBatchRwdextraJson() {
        List<RwdextraExtend> rwdextraList = rwdextraExtendMapper.getList(new RwdextraExtend().setPlantimeStart("2024-12-26"));
        for (RwdextraExtend entity : rwdextraList) {
            if (entity != null) {
                Rwdextra rwdextra = rwdextraService.selectByFrwdh(entity.getFrwdh());
                RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
                if (entity.getOpenAppraisalId() == null && entity.getPrintJson() != null && rwdextraPrintInfo.getMixProportionInfo() != null) {
                    /**配合比信息**/
                    MixProportion mixProportion = rwdextraPrintInfo.getMixProportionInfo();
                    /**保存任务单扩展表对应打印信息**/
                    setMixProportionPktzId(mixProportion, rwdextra);
                    rwdextraPrintInfo.setMixProportionInfo(mixProportion);
                    entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
                    entity.setUpdateTime(new Date());
                    rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
                }
            }
        }
    }

    @Override
    public void updateBatchLlzhl(String frwno) {
        List<Rwdextra> rwdextraList = rwdextraMapper.getList(new Rwdextra().setFrwno(frwno));
        for (Rwdextra rwdextra : rwdextraList) {
            RwdextraExtend entity = rwdextraExtendMapper.selectByFRwdh(rwdextra.getFrwdh());
            Rwdextra rwdextraLlzhl = rwdextraService.selectByFrwdh(rwdextra.getFrwdh());
            assertTrue((entity == null || entity.getPrintJson() == null), "任务单未修改配合比");
            RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);

            if (rwdextraLlzhl.getRwdextraInfo() != null && StringUtils.isNotBlank(rwdextraLlzhl.getRwdextraInfo().getFTbj())) {

                String fTbj = rwdextraLlzhl.getRwdextraInfo().getFTbj();

                String kllzhl = ConvertUtils.getKllzhl(fTbj);
                if (StringUtils.isNotBlank(kllzhl)) {
                    rwdextraPrintInfo.setLlzhl(kllzhl);
                    entity.setLlzHl(kllzhl);
                }
            }
            entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
            rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
        }
    }

    /**
     * 1、如果有验证记录，则显示与验证记录有关的试验台账ID
     * 2、如果对应工程有绑定物料，则显示对应物料的试验台账ID
     * 3、否则选择非甲供的物料的试验台账ID
     *
     * @param mixProportion 配合比原材料信息
     * @param rwdextra      任务单号
     * @return
     */
    @Override
    public void setMixProportionPktzId(MixProportion mixProportion, Rwdextra rwdextra) {
        JSONObject proportionMaterial = mixProportion.getProportionMaterial();
        if (proportionMaterial == null) {
            return;
        }
        /** 未生产，取计划时间
         第一车生成完成 取生产时间*/
        RwdextraExtend entity = rwdextra.getRwdextraExtend();
        Date planTime;
        if (entity.getSupplyStartTime() != null) {
            planTime = entity.getSupplyStartTime();
        } else {
            planTime = rwdextra.getPlantime();
        }
        /*RwdextraInfo rwdextraInfo = rwdextra.getRwdextraInfo();
        String fGcmc = rwdextraInfo.getFGcmc();*/
        Long projectId = rwdextra.getRwdextraExtend().getErpProjectId();
        /**这里根据工程名称(改为工程ID)+配合比唯一标识 查询配合比验证记录 一个配合比同一个工程只能有一条记录*/
        MixProportionVerifyRecord verifyRecord = mixProportionVerifyRecordMapper.selectByMixIdAndProjectId(mixProportion.getId(), projectId);
        ErpProject project = erpProjectMapper.loadById(entity.getErpProjectId());
        ProjectMaterialsReport projectMaterialsReport = new ProjectMaterialsReport();
        if (project != null && project.getProjectMaterial() != null) {
            projectMaterialsReport = JsonUtils.getObject(project.getProjectMaterial(), ProjectMaterialsReport.class);
        }
        MixProportionReport mixProportionReport = JsonUtils.getObject(proportionMaterial, MixProportionReport.class);
        MixProportionReport.BgxxInfo sn = mixProportionReport.getSn();//水泥
        this.getPrintTaskExperimentInfo(sn, planTime, verifyRecord == null ? null : verifyRecord.getSnFactory(),
                verifyRecord == null ? null : verifyRecord.getSnFactoryCalled(),
                verifyRecord == null ? null : verifyRecord.getSnSupplier(),
                verifyRecord == null ? null : verifyRecord.getSnSupplierCalled(),
                projectMaterialsReport == null ? null : projectMaterialsReport.getSn());
        mixProportionReport.setSn(sn);

        MixProportionReport.BgxxInfo fmh = mixProportionReport.getFmh();//粉煤灰
        this.getPrintTaskExperimentInfo(fmh, planTime, verifyRecord == null ? null : verifyRecord.getFmh1Factory(),
                verifyRecord == null ? null : verifyRecord.getFmh1FactoryCalled(),
                verifyRecord == null ? null : verifyRecord.getFmh1Supplier(),
                verifyRecord == null ? null : verifyRecord.getFmh1SupplierCalled(), projectMaterialsReport == null ? null : projectMaterialsReport.getFmh());
        mixProportionReport.setFmh(fmh);

        MixProportionReport.BgxxInfo kzf = mixProportionReport.getKzf();//矿渣粉
        this.getPrintTaskExperimentInfo(kzf, planTime, verifyRecord == null ? null : verifyRecord.getKzf1Factory(),
                verifyRecord == null ? null : verifyRecord.getKzf1FactoryCalled(),
                verifyRecord == null ? null : verifyRecord.getKzf1Supplier(),
                verifyRecord == null ? null : verifyRecord.getKzf1SupplierCalled(), projectMaterialsReport == null ? null : projectMaterialsReport.getKzf());
        mixProportionReport.setKzf(kzf);

        MixProportionReport.BgxxInfo cgl = mixProportionReport.getCgl();//粗骨料
        this.getPrintTaskExperimentInfo(cgl, planTime, verifyRecord == null ? null : verifyRecord.getCglFactory(),
                verifyRecord == null ? null : verifyRecord.getCglFactoryCalled(),
                verifyRecord == null ? null : verifyRecord.getCglSupplier(),
                verifyRecord == null ? null : verifyRecord.getCglSupplierCalled(), projectMaterialsReport == null ? null : projectMaterialsReport.getCgl());
        mixProportionReport.setCgl(cgl);

        MixProportionReport.BgxxInfo xgl = mixProportionReport.getXgl();//细骨料
        this.getPrintTaskExperimentInfo(xgl, planTime, verifyRecord == null ? null : verifyRecord.getXglFactory(),
                verifyRecord == null ? null : verifyRecord.getXglFactoryCalled(),
                verifyRecord == null ? null : verifyRecord.getXglSupplier(),
                verifyRecord == null ? null : verifyRecord.getXglSupplierCalled(), projectMaterialsReport == null ? null : projectMaterialsReport.getXgl());
        mixProportionReport.setXgl(xgl);

        MixProportionReport.BgxxInfo wjj1 = mixProportionReport.getWjj1();//外加剂1
        this.getPrintTaskExperimentInfo(wjj1, planTime, verifyRecord == null ? null : verifyRecord.getWjj1Factory(),
                verifyRecord == null ? null : verifyRecord.getWjj1FactoryCalled(),
                verifyRecord == null ? null : verifyRecord.getWjj1Supplier(),
                verifyRecord == null ? null : verifyRecord.getWjj1SupplierCalled(), projectMaterialsReport == null ? null : projectMaterialsReport.getWjj1());
        mixProportionReport.setWjj1(wjj1);

        MixProportionReport.BgxxInfo wjj2 = mixProportionReport.getWjj2();//外加剂2
        this.getPrintTaskExperimentInfo(wjj2, planTime, verifyRecord == null ? null : verifyRecord.getWjj2Factory(),
                verifyRecord == null ? null : verifyRecord.getWjj2FactoryCalled(),
                verifyRecord == null ? null : verifyRecord.getWjj2Supplier(),
                verifyRecord == null ? null : verifyRecord.getWjj2SupplierCalled(), projectMaterialsReport == null ? null : projectMaterialsReport.getWjj2());
        mixProportionReport.setWjj2(wjj2);

        MixProportionReport.BgxxInfo wcl1 = mixProportionReport.getWcl1();//外掺料1
        this.getPrintTaskInfo(1, wcl1, verifyRecord, projectMaterialsReport == null ? null : projectMaterialsReport.getWcl1());
        mixProportionReport.setWcl1(wcl1);

        MixProportionReport.BgxxInfo wcl2 = mixProportionReport.getWcl2();//外掺料2
        this.getPrintTaskInfo(2, wcl2, verifyRecord, projectMaterialsReport == null ? null : projectMaterialsReport.getWcl2());
        mixProportionReport.setWcl2(wcl2);

        mixProportion.setProportionMaterial(JsonUtils.beanToObject(mixProportionReport));
    }

    /**
     * 外掺料特殊处理
     *
     * @param bgxxInfo 配合比原材料信息
     * @return
     */
    private void getPrintTaskInfo(int type, MixProportionReport.BgxxInfo bgxxInfo, MixProportionVerifyRecord verifyRecord, ProjectMaterialsReport.MaterialsInfo materialsInfo) {
        /** 配合比的生产方量大于0 才走该逻辑 **/
        if (bgxxInfo != null && StringUtils.isNotBlank(bgxxInfo.getScyl()) && NullUtils.isNumberGreaterThanZero(bgxxInfo.getScyl())) {
            if (type == 1) {
                if (verifyRecord != null) {
                    /**当配合比存在验证记录 **/
                    if (StringUtils.isNotBlank(verifyRecord.getWcl1Factory())) {
                        bgxxInfo.setCj(verifyRecord.getWcl1Factory());
                        bgxxInfo.setCjjc(verifyRecord.getWcl1FactoryCalled());
                    }
                    if (StringUtils.isNotBlank(verifyRecord.getWcl1Supplier())) {
                        bgxxInfo.setGys(verifyRecord.getWcl1Supplier());
                        bgxxInfo.setGysjc(verifyRecord.getWcl1SupplierCalled());
                    }
                    return;
                }
            }
            if (type == 2) {
                if (verifyRecord != null) {
                    /**当配合比存在验证记录 **/
                    if (StringUtils.isNotBlank(verifyRecord.getWcl2Factory())) {
                        bgxxInfo.setCj(verifyRecord.getWcl2Factory());
                        bgxxInfo.setCjjc(verifyRecord.getWcl2FactoryCalled());
                    }
                    if (StringUtils.isNotBlank(verifyRecord.getWcl2Supplier())) {
                        bgxxInfo.setGys(verifyRecord.getWcl2Supplier());
                        bgxxInfo.setGysjc(verifyRecord.getWcl2SupplierCalled());
                    }
                    return;
                }
            }
            if (StringUtils.isNotBlank(materialsInfo.getCllx()) && materialsInfo.getWlmc().equals(bgxxInfo.getWlmc()) && materialsInfo.getWlgg().equals(bgxxInfo.getWlgg())) {
                /**当工程存在绑定原材料记录 **/
                if (StringUtils.isNotBlank(materialsInfo.getCj())) {
                    bgxxInfo.setCj(materialsInfo.getCj());
                    bgxxInfo.setCjjc(materialsInfo.getCjjc());
                }
                if (StringUtils.isNotBlank(materialsInfo.getGys())) {
                    bgxxInfo.setGys(materialsInfo.getGys());
                    bgxxInfo.setGysjc(materialsInfo.getGysjc());
                }
            }
        }

    }

    /**
     * 根据配合中 材料名称+材料规格+材料类型 获取任务单的计划时间之前最近的一条
     *
     * @param bgxxInfo 配合比原材料信息
     * @param planTime 任务单号
     * @return
     */
    private void getPrintTaskExperimentInfo(MixProportionReport.BgxxInfo bgxxInfo, Date planTime, String factory, String factoryCalled, String supplier, String supplierCalled, ProjectMaterialsReport.MaterialsInfo materialsInfo) {
        /*String clmc = bgxxInfo.getClmc();//材料名称
        String clgg = bgxxInfo.getClgg();//材料规格
        String cllx = bgxxInfo.getCllx();//材料类型*/
        String wlmc = bgxxInfo.getWlmc();//物料名称
        String wlgg = bgxxInfo.getWlgg();//物料规格
        /* String wllx = bgxxInfo.getWllx();//物料类型*/
        if (StringUtils.isBlank(wlmc) || StringUtils.isBlank(wlgg)) {
            return;
        }
        ExperimentPrintVo experimentPrintVo = new ExperimentPrintVo().setWlmc(wlmc).setWlgg(wlgg).setPlanTime(planTime);
        Experiment experiment;
        SystemParam systemParam = systemParamMapper.selectBySystemCode(SystemParamEnum.IS_PRODUCTION_ISSUANCE);
        if (systemParam == null || "0".equals(systemParam.getSystemValue())) {
            if (StringUtils.isNotBlank(factory)) {
                /**当配合比存在验证记录 任务单工程名称配合比验证记录相同  得到指定厂家的原材料报告**/
                experimentPrintVo.setFactory(factory);
                experiment = experimentMapper.getLastExperimentIdByFactory(experimentPrintVo);
            } else if (materialsInfo != null && StringUtils.isNotBlank(materialsInfo.getCllx()) && materialsInfo.getWlmc().equals(experimentPrintVo.getWlmc()) && materialsInfo.getWlgg().equals(experimentPrintVo.getWlgg())) {
                experimentPrintVo.setMaterialsValue(experimentPrintVo, materialsInfo);
                /**当对应工程有绑定物料, 并且物料名称 物料规格相同 根据物料  得到指定厂家的原材料报告**/
                experiment = experimentMapper.getLastExperimentIdByFactoryAndSupplyCompanyName(experimentPrintVo);
            } else {
                /**获取条件为非甲供  得到指定厂家的原材料报告**/
                experimentPrintVo.setSelfSupply(SelfSupplyEnum.YES.getCode());
                experiment = experimentMapper.getLastExperimentIdNotSelfSupply(experimentPrintVo);
            }
            if (experiment != null) {
                bgxxInfo.setPktzid(NullUtils.ifNull(experiment.getId()));
                bgxxInfo.setXhbgbh(experiment.getReportNo());
                bgxxInfo.setCj(experiment.getFactory());
                bgxxInfo.setCjjc(experiment.getFactoryCalled());
                bgxxInfo.setGys(experiment.getSupplyCompanyName());
                bgxxInfo.setGysjc(experiment.getSupplyCompanyCalled());
                bgxxInfo.setClmc(experiment.getMaterialsName());
                bgxxInfo.setClgg(experiment.getMaterialsSpecs());
            } else {
                bgxxInfo.setPktzid("");
                bgxxInfo.setXhbgbh("");
                bgxxInfo.setCj("");
                bgxxInfo.setCjjc("");
                bgxxInfo.setGys("");
                bgxxInfo.setGysjc("");
                bgxxInfo.setClmc("");
                bgxxInfo.setClgg("");
            }
        } else {
            /**获取条件为非甲供  得到指定厂家的原材料报告**/
            experimentPrintVo.setSelfSupply(SelfSupplyEnum.YES.getCode());
            experiment = experimentMapper.getLastExperimentIdNotSelfSupply(experimentPrintVo);
            if (experiment != null) {
                bgxxInfo.setPktzid(NullUtils.ifNull(experiment.getId()));
                bgxxInfo.setXhbgbh(experiment.getReportNo());
                bgxxInfo.setCj(experiment.getFactory());
                bgxxInfo.setCjjc(experiment.getFactoryCalled());
                bgxxInfo.setGys(experiment.getSupplyCompanyName());
                bgxxInfo.setGysjc(experiment.getSupplyCompanyCalled());
                bgxxInfo.setClmc(experiment.getMaterialsName());
                bgxxInfo.setClgg(experiment.getMaterialsSpecs());
            }
            if (StringUtils.isNotBlank(factory)) {
                bgxxInfo.setPktzid("");
                bgxxInfo.setCj(factory);
                bgxxInfo.setCjjc(factoryCalled);
                bgxxInfo.setGys(supplier);
                bgxxInfo.setGysjc(supplierCalled);
            } else if (materialsInfo != null && StringUtils.isNotBlank(materialsInfo.getCllx()) && materialsInfo.getWlmc().equals(experimentPrintVo.getWlmc()) && materialsInfo.getWlgg().equals(experimentPrintVo.getWlgg())) {
                bgxxInfo.setPktzid("");
                bgxxInfo.setCj(materialsInfo.getCj());
                bgxxInfo.setCjjc(materialsInfo.getCjjc());
                bgxxInfo.setGys(materialsInfo.getGys());
                bgxxInfo.setGysjc(materialsInfo.getGysjc());
            }
        }

    }

    @Override
    public void updateSupplyEndTime(RwdextraExtend entity) {
        entity.setSupplyEndTime(new Date());
        rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void isPrint(Integer frwdh) {
        RwdextraExtend entity = rwdextraExtendMapper.selectByFRwdh(frwdh);
        if (entity == null) {
            entity = new RwdextraExtend();
            entity.setId(null);
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setPrintStatus(1);
            entity.setFrwdh(frwdh);
            rwdextraExtendMapper.insertSelective(entity);
        } else {
            entity.setUpdateTime(new Date());
            entity.setPrintStatus(1);
            rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
        }
    }

    @Override
    public List<RwdextraExtend> updateBatch(RwdextraExtend entity) {
        List<RwdextraExtend> list = new ArrayList<>();
        List<Integer> frwdhList = entity.getFrwdhList();
        for (Integer frwdh : frwdhList) {
            try {
                RwdextraExtend extendInfo = rwdextraExtendMapper.selectByFRwdh(frwdh);

                RwdextraExtend afterInfo = new RwdextraExtend();
                if (extendInfo == null) {
                    afterInfo.setErpCustomerId(entity.getErpCustomerId());
                    afterInfo.setErpProjectId(entity.getErpProjectId());
                    afterInfo.setProjectName(entity.getProjectName());
                    afterInfo.setBuildName(entity.getBuildName());
                    afterInfo.setXglHsl(entity.getXglHsl());
                    afterInfo.setCglHsl(entity.getCglHsl());
                    afterInfo.setLlzHl(entity.getLlzHl());
                    afterInfo.setCreateTime(new Date());
                    afterInfo.setUpdateTime(new Date());
                    rwdextraExtendMapper.insertSelective(afterInfo);
                } else {
                    afterInfo = new RwdextraExtend();
                    BeanUtils.copyProperties(extendInfo, afterInfo);
                    afterInfo.setUpdateTime(new Date());
                    afterInfo.setIsGenXnbg(extendInfo.getIsGenXnbg());
                    afterInfo.setErpCustomerId(entity.getErpCustomerId());
                    afterInfo.setErpProjectId(entity.getErpProjectId());
                    afterInfo.setProjectName(entity.getProjectName());
                    afterInfo.setBuildName(entity.getBuildName());
                    afterInfo.setXglHsl(entity.getXglHsl());
                    afterInfo.setCglHsl(entity.getCglHsl());
                    afterInfo.setLlzHl(entity.getLlzHl());
                    afterInfo.setUpdateTime(new Date());
                    rwdextraExtendMapper.updateByPrimaryKeySelective(afterInfo);
                }
                /**这里添加日志 记录修改前和修改后的*/
                rwdextraExtendUpdateLogService.insertLog(frwdh, extendInfo, afterInfo);

                /**这里添加任务单的修改记录*/
                rwdextraUpdateLogService.insertLog(frwdh, null);

                list.add(afterInfo);
            } catch (Exception e) {
                log.error("批量修改ERP任务单扩展信息失败，任务单号：【{}】", frwdh, e);
            }
        }
        return list;
    }

    @Override
    public List<RwdextraExtend> updateBatchPrint(RwdextraExtend entity) {
        List<Integer> frwdhList = entity.getFrwdhList();
        List<RwdextraExtend> list = new ArrayList<>();
        for (Integer frwdh : frwdhList) {
            RwdextraExtend extendInfo = rwdextraExtendMapper.selectByFRwdh(frwdh);
            assertTrue(extendInfo.getPrintJson() == null, "任务单未完成第一车小票生产");

            RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(extendInfo.getPrintJson(), RwdextraPrintInfo.class);
            RwdextraPrintInfo rwdextraPrintInfoNew = JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
            rwdextraPrintInfo.setUpdate(rwdextraPrintInfo, rwdextraPrintInfoNew);
            /**这里修改了需要改变状态 增补资料标识*/
            rwdextraExtendMapper.updateByPrimaryKeySelective(extendInfo.setIsAddInformation(1).setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo)));

            RwdextraExtend afterInfo = new RwdextraExtend();
            rwdextraPrintInfo.setValue(rwdextraPrintInfo, rwdextraPrintInfoNew);
            /**抗压台账*/
            List<RwdextraPrintInfo.Kytz> kyInfoList = rwdextraPrintInfo.getKyInfoList();
            if (CollectionUtil.isNotEmpty(kyInfoList)) {
                for (RwdextraPrintInfo.Kytz kytz : kyInfoList) {
                    if (StringUtils.isNotBlank(kytz.getXhwtbh())) {
                        ShxhSynchronizedata shxhSynchronizedata = shxhSynchronizedataMapper.selectByConsignId(kytz.getXhwtbh());
                        List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(shxhSynchronizedata.getExperimentId(), TestProjectEnum.CONCRETE_PARAM_KYQD.getCode());
                        if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                            /**将json转成对象*/
                            ConcreteKyqd concreteKyqd = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteKyqd.class);
                            kytz.setQdpjz(concreteKyqd.getFyxs28d());
                        }
                    }
                }
            }
            rwdextraPrintInfo.setKyInfoList(kyInfoList);
            /** 如果配合比修改了 再更新一遍关联数据
             Rwdextra rwdextra = rwdextraService.selectByFrwdh(frwdh);
             RwdextraInfo rwdextraInfo = RwdextraInfo.jsonToObj(rwdextra.getExtrainfo());
             if (rwdextraPrintInfoNew.getMixProportion() != null && !NullUtils.isNull(rwdextraPrintInfoNew.getMixProportion().getProportionPhb())) {
             if (!rwdextraPrintInfoNew.getMixProportion().getProportionPhb().equals(rwdextraInfo.getFPhbNo())) {
             setMixProportionPktzId(rwdextraPrintInfoNew.getMixProportion(), rwdextra);
             rwdextraPrintInfo.getCustomer().setFPhbNo(rwdextraPrintInfoNew.getMixProportion().getProportionPhb());
             }
             }**/
            rwdextraPrintInfo.setMixProportionInfo(rwdextraPrintInfoNew.getMixProportion());
            rwdextraPrintInfo.getCustomer().setFPhbNo(rwdextraPrintInfoNew.getMixProportion().getProportionPhb());
            entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
            afterInfo.setFrwdh(frwdh);
            afterInfo.setId(extendInfo.getId());
            if (rwdextraPrintInfoNew.getCustomer() != null) {
                afterInfo.setErpCustomerId(NullUtils.ifNullLong(rwdextraPrintInfoNew.getCustomer().getErpCustomerId()));
                afterInfo.setErpProjectId(NullUtils.ifNullLong(rwdextraPrintInfoNew.getCustomer().getErpProjectId()));
            }
            afterInfo.setProjectName(rwdextraPrintInfoNew.getCustomer().getProjectName());
            afterInfo.setBuildName(rwdextraPrintInfoNew.getCustomer().getBuildName());
            afterInfo.setXglHsl(entity.getXglHsl());
            afterInfo.setCglHsl(entity.getCglHsl());
            afterInfo.setLlzHl(rwdextraPrintInfoNew.getLlzhl());
            afterInfo.setPrintJson(entity.getPrintJson());
            afterInfo.setLlzHl(rwdextraPrintInfoNew.getLlzhl());
            afterInfo.setUpdateTime(new Date());
            afterInfo.setPlanQuantity(rwdextraPrintInfoNew.getPlanQuantity());
            afterInfo.setPouringPosition(rwdextraPrintInfoNew.getPouringPosition());
            afterInfo.setFWcsl(entity.getFWcsl());
            afterInfo.setPlantimeStart(entity.getPlantimeStart());
            afterInfo.setSupplyStartTime(rwdextraPrintInfoNew.getCustomer().getSupplyStartTime());
            afterInfo.setSupplyEndTime(rwdextraPrintInfoNew.getCustomer().getSupplyEndTime());
            afterInfo.setCreateTime(extendInfo.getCreateTime());
            if (StringUtils.isNotBlank(rwdextraPrintInfoNew.getCchgzbh())) {
                afterInfo.setQualityCertificateNo(rwdextraPrintInfoNew.getCchgzbh());
            } else {
                afterInfo.setQualityCertificateNo(extendInfo.getQualityCertificateNo());
            }
            afterInfo.setOpenAppraisalId(extendInfo.getOpenAppraisalId());
            /**这里不需要修改任务单扩展记录表只需要添加修改记录  2025-02-27 21:22 跟李总开会沟通*/
            //rwdextraExtendMapper.updateByPrimaryKeySelective(afterInfo);
            /**这里添加日志 记录修改前和修改后的*/
            rwdextraExtendUpdateLogService.insertLog(frwdh, extendInfo, afterInfo);

            /**这里添加任务单的修改记录*/
            rwdextraUpdateLogService.insertLog(frwdh, null);
            list.add(afterInfo);
        }
        return list;
    }

    @Override
    public List<RwdextraExtend> updateBatchPrintDetailRwdextra(RwdextraExtendUpdateDto entity) {
        List<Integer> frwdhList = entity.getFrwdhList();
        for (Integer frwdh : frwdhList) {
            RwdextraExtend extendInfo = rwdextraExtendMapper.selectByFRwdh(frwdh);
            if (extendInfo == null) {
                continue;
            }
            RwdextraPrintInfo rwdextraPrintInfo;
            if (extendInfo.getPrintJson() == null || extendInfo.getPrintJson().isEmpty()) {
                rwdextraPrintInfo = new RwdextraPrintInfo();
            } else {
                rwdextraPrintInfo = JsonUtils.getObject(extendInfo.getPrintJson(), RwdextraPrintInfo.class);
            }
            /**这里修改了需要改变状态 增补资料标识*/
            rwdextraExtendMapper.updateByPrimaryKeySelective(new RwdextraExtend().setId(extendInfo.getId()).setIsAddInformation(1).setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo)));
            RwdextraExtend afterInfo = extendInfo;
            afterInfo.setProjectName(entity.getProjectName());
            afterInfo.setContractName(entity.getCustomerName());
            RwdextraPrintInfo.Customer customer = rwdextraPrintInfo.getCustomer() == null ? new RwdextraPrintInfo.Customer() : rwdextraPrintInfo.getCustomer();
            customer.setCustomerName(entity.getCustomerName());
            customer.setProjectName(entity.getProjectName());
            rwdextraPrintInfo.setCustomer(customer);
            afterInfo.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
            /**这里添加日志 记录修改前和修改后的*/
            rwdextraExtendUpdateLogService.insertLog(frwdh, extendInfo, afterInfo);

            /**这里添加任务单的修改记录*/
            rwdextraUpdateLogService.insertLog(frwdh, null);
        }
        return null;
    }

    @Override
    public RwdextraExtend generateReport(RwdextraExtend entity) {
        List<Integer> frwdhList = entity.getFrwdhList();
        assertTrue(CollectionUtil.isEmpty(frwdhList), "未选择任务单");
        Integer frwdh = frwdhList.get(0);
        RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
        Rwdextra rwdextra = rwdextraService.selectByFrwdh(frwdh);
        assertTrue(rwdextraPrintInfo.getMixProportion() == null, "未选择配合比");
        assertTrue(rwdextraPrintInfo.getCustomer().getPlantimeStart() == null, "未选择计划日期");
        Date planTime = DateHelper.parseDateList(rwdextraPrintInfo.getCustomer().getPlantimeStart());
        assertTrue(planTime == null, "计划日期格式错误");
        entity.setPouringPosition(rwdextraPrintInfo.getPouringPosition());
        entity.setPlanQuantity(rwdextraPrintInfo.getPlanQuantity());
        setRwdextraValue(entity, rwdextra);
        entity.setRwdextra(rwdextra);
        MixProportion mixProportion = rwdextraPrintInfo.getMixProportion();
        /** 配合比 都需要取最近一条原材料台账的信息 包括报告编号 材料物料信息 厂商供应商信息 **/
        rwdextraExtendService.setMixProportionPktzId(mixProportion, rwdextra);
        if (mixProportion != null) {
            rwdextraPrintInfo.setMixProportion(mixProportion);
            rwdextraPrintInfo.setMixProportionInfo(mixProportion);
        }
        String projectName = rwdextra.getRwdextraInfo().getFGcmc();
        String proportionPhb = mixProportion.getProportionPhb();
        String year = rwdextra.getRwdextraInfo().getFRwno().substring(0, 4);
        /** 计划日期之前的 同配合比的抗压报告 （完成方量 与生成委托规则抗压的按方量 取模 如果有余数 +1） **/
        ExperimentGenConfig genConfigKy = experimentGenConfigMapper.selectOne(new ExperimentGenConfig()
                .setTestCode(KY_TEST_PROJECT_CODE).setExperimentType(MaterialsEnum.CONCRETE.getCode()));
        ExperimentDetailDto experimentDetailDto = new ExperimentDetailDto();
        experimentDetailDto.setPlanTime(planTime);
        experimentDetailDto.setTestProjectCode(KY_TEST_PROJECT_CODE);
        /*experimentDetailDto.setFGcmc(projectName);*/
        experimentDetailDto.setFPhbNo(proportionPhb);
        if (genConfigKy.getCheckRules() == 2) {
            String fhquantity = rwdextraPrintInfo.getCustomer().getFhquantity();
            if(StringUtils.isNotBlank(fhquantity) && StringUtils.isNotBlank(genConfigKy.getCheckThreshold())) {
                double wcsl = Double.valueOf(fhquantity);
                double fz = Double.valueOf(genConfigKy.getCheckThreshold());
                int quotient = (int) (wcsl / fz);//; 计算商
                double remainder = wcsl % fz; // 计算余数
                if (remainder != 0) {
                    quotient++;
                }
                experimentDetailDto.setLimit(quotient);
            }else{
                experimentDetailDto.setLimit(0);
            }
        }
        List<Long> kyExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCodeRwdUpdate(experimentDetailDto);
        if (!kyExperimentIdList.isEmpty()) {
            List<String> kytzList = new ArrayList();
            List<RwdextraPrintInfo.Kytz> kyInfoList = new ArrayList();
            for (Long experimentId : kyExperimentIdList) {
                RwdextraPrintInfo.Kytz kytz = new RwdextraPrintInfo.Kytz();
                Experiment experiment = experimentMapper.loadById(experimentId);
                if (experiment != null) {
                    if (StringUtils.isNotBlank(experiment.getSampleId())) {
                        kytzList.add(experiment.getSampleId());
                    } else {
                        kytzList.add(experiment.getExperimentNo());
                    }
                    kytz.setWtbh(experiment.getExperimentNo());
                    kytz.setXhwtbh(experiment.getConsignId());
                    kytz.setYpbh(experiment.getSampleId());
                    kytz.setSytzbh(String.valueOf(experiment.getId()));
                    List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_KYQD.getCode());
                    if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                        /**将json转成对象*/
                        ConcreteKyqd concreteKyqd = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteKyqd.class);
                        kytz.setQdpjz(concreteKyqd.getPjz28d());
                        kytz.setDdsjqd(concreteKyqd.getFyxs28d());
                        kytz.setZsbzqd(concreteKyqd.getZsbzqd28d());
                    }
                    kyInfoList.add(kytz);
                }
            }
            rwdextraPrintInfo.setKytzList(kytzList);
            rwdextraPrintInfo.setKyInfoList(kyInfoList);
        } else {
            rwdextraPrintInfo.setKytzList(new ArrayList());
            rwdextraPrintInfo.setKyInfoList(new ArrayList());
        }
        /** 抗折报告（一条 可能多条）  **/
        experimentDetailDto.setLimit(1);
        experimentDetailDto.setTestProjectCode(KZ_TEST_PROJECT_CODE);
        List<Long> kzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCodeRwdUpdate(experimentDetailDto);
        if (!kzExperimentIdList.isEmpty()) {
            Long experimentId = kzExperimentIdList.get(0);
            rwdextraPrintInfo.setKzExperimentId(experimentId);
            Experiment experiment = experimentMapper.loadById(experimentId);
            if (experiment != null) {
                rwdextraPrintInfo.setKztzypbh(experiment.getSampleId());
                rwdextraPrintInfo.setKztzwtbh(experiment.getExperimentNo());
            }
        } else {
            rwdextraPrintInfo.setKzExperimentId(null);
            rwdextraPrintInfo.setKztzypbh(null);
            rwdextraPrintInfo.setKztzwtbh(null);
        }
        /** 抗渗报告（一条 同工程同配合比，生成委托规则中是否选择了限定为当年）  **/
        ExperimentGenConfig genConfigKs = experimentGenConfigMapper.selectOne(new ExperimentGenConfig()
                .setTestCode(KS_TEST_PROJECT_CODE).setExperimentType(MaterialsEnum.CONCRETE.getCode()));
        if (genConfigKs.getIsYear() == 1) {
            experimentDetailDto.setYear(year);
        }
        /** 如果客户输入了抗渗等级 通过抗渗等级获取对应的试验台账 **/
        if (StringUtils.isNotBlank(rwdextraPrintInfo.getKsdj()) && !rwdextraPrintInfo.getKsdj().equals(rwdextra.getRwdextraInfo().getKsdj())) {
            experimentDetailDto.setKsdj(rwdextraPrintInfo.getKsdj());
            rwdextra.getRwdextraInfo().setKsdj(rwdextraPrintInfo.getKsdj());
            experimentDetailDto.setFGcmc(projectName);
            experimentDetailDto.setLimit(1);
            experimentDetailDto.setTestProjectCode(KS_TEST_PROJECT_CODE);
            List<Long> ksExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCodeRwdUpdate(experimentDetailDto);
            if (!ksExperimentIdList.isEmpty()) {
                Long experimentId = ksExperimentIdList.get(0);
                rwdextraPrintInfo.setKsExperimentId(experimentId);
                Experiment experiment = experimentMapper.loadById(experimentId);
                if (experiment != null) {
                    rwdextraPrintInfo.setKstzypbh(experiment.getSampleId());
                    rwdextraPrintInfo.setKstzwtbh(experiment.getExperimentNo());
                }
            } else {
                rwdextraPrintInfo.setKsExperimentId(null);
                rwdextraPrintInfo.setKstzypbh(null);
                rwdextraPrintInfo.setKstzwtbh(null);
            }
        }/*else{
            rwdextraPrintInfo.setKsExperimentId(null);
            rwdextraPrintInfo.setKstzypbh(null);
            rwdextraPrintInfo.setKstzwtbh(null);
        }*/
        /** 抗氯离子报告（一条 同工程同配合比，生成委托规则中是否选择了限定为当年）  **/
        ExperimentGenConfig genConfigLlzhl = experimentGenConfigMapper.selectOne(new ExperimentGenConfig()
                .setTestCode(LLZHL_TEST_PROJECT_CODE).setExperimentType(MaterialsEnum.CONCRETE.getCode()));
        if (genConfigLlzhl.getIsYear() == 1) {
            experimentDetailDto.setYear(year);
        }
        experimentDetailDto.setTestProjectCode(LLZHL_TEST_PROJECT_CODE);
        List<Long> kllzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCodeRwdUpdate(experimentDetailDto);
        if (!kllzExperimentIdList.isEmpty()) {
            log.info("存在氯离子绑定台账的任务单【{}】", frwdh);
            rwdextraPrintInfo.setKllExperimentId(kllzExperimentIdList.get(0));
        } else {
            kllzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCodeRwdUpdate(experimentDetailDto);
            if (!kllzExperimentIdList.isEmpty()) {
                rwdextraPrintInfo.setKllExperimentId(kllzExperimentIdList.get(0));
                log.info("不存在氯离子绑定台账的任务单【{}】 绑定试验台账ID :【{}】", frwdh, kllzExperimentIdList);
            } else {
                log.info("未找到氯离子绑定台账的任务单【{}】", frwdh);
            }
        }
        if (rwdextraPrintInfo.getKllExperimentId() != null) {
            Long experimentId = rwdextraPrintInfo.getKllExperimentId();
            rwdextraPrintInfo.setKllExperimentId(experimentId);
            Experiment experiment = experimentMapper.loadById(experimentId);
            if (experiment != null) {
                rwdextraPrintInfo.setKllztzypbh(experiment.getSampleId());
                rwdextraPrintInfo.setKllztzwtbh(experiment.getExperimentNo());
            }
        } else {
            rwdextraPrintInfo.setKllExperimentId(null);
            rwdextraPrintInfo.setKllztzypbh(null);
            rwdextraPrintInfo.setKllztzwtbh(null);
        }

        /** 出厂证明签发日期 赋值  **/
        Date supplyStartTime = rwdextraPrintInfo.getCustomer().getSupplyStartTime();
        /** 如果没有供货日期，就取计划时间  **/
        if(supplyStartTime == null){
            supplyStartTime = DateHelper.parseDateTime(rwdextra.getRwdextraInfo().getFJhrq());
        }
        if (supplyStartTime != null && StringUtils.isNotBlank(mixProportion.getProportionLq()) && CollectionUtil.isNotEmpty(kyExperimentIdList)) {
            Date entrustTime = experimentMapper.getMaxExperimentEntrustTime(kyExperimentIdList);
            int lq = Integer.parseInt(mixProportion.getProportionLq());
            int dateNum;
            if (rwdextraPrintInfo.getKsExperimentId() != null) {
                /** 有抗渗*/
                Experiment experiment = experimentMapper.loadById(rwdextraPrintInfo.getKsExperimentId());
                /** 报告日期不为空*/
                if (experiment != null && experiment.getReportDate() != null) {
                    Date ksReportDate = experiment.getReportDate();
                    /** 报告日期<=供应日期，那么，签发日期就是供应日期+1*/
                    if (DateHelper.daysBetween(supplyStartTime, ksReportDate) <= 0) {
                        rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(supplyStartTime, Calendar.DATE, 1, "yyyy-MM-dd"));
                    } else {
                        /** 报告日期>供应日期，那么签发日期=抗压最后一组委托的委托日期+配合比龄期+(P63天，P84天，P105天，P12，6天)*/
                        dateNum = lq + KsLqEnum.selectByName(rwdextraPrintInfo.getKsdj()).getLq();
                        rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(entrustTime, Calendar.DATE, dateNum, "yyyy-MM-dd"));
                    }
                } else {
                    /** 报告日期为空，那么签发日期=抗压最后一组委托的委托日期+配合比龄期+(P63天，P84天，P105天，P12，6天)*/
                    dateNum = lq + KsLqEnum.selectByName(rwdextraPrintInfo.getKsdj()).getLq();
                    rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(entrustTime, Calendar.DATE, dateNum, "yyyy-MM-dd"));
                }
            } else {
                /** 没有抗渗*/
                Date entrustTimeLq = DateHelper.addDate(entrustTime, Calendar.DATE, lq);
                Date supplyStartTimeKy = DateHelper.addDate(supplyStartTime, Calendar.DATE, 1);
                if (DateHelper.daysBetween(entrustTimeLq, supplyStartTimeKy) >= 0 && CollectionUtil.isNotEmpty(kyExperimentIdList)) {
                    /** 最后一个抗压委托的委托日期+配合比龄期>=供应日期时 签发日期=签发日期=抗压委托报告时间+1*/
                    Date reportDate = experimentMapper.getMaxExperimentReportDate(kyExperimentIdList);
                    if (reportDate != null) {
                        rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(reportDate, Calendar.DATE, 1, "yyyy-MM-dd"));
                    }
                } else {
                    /** 最后一个抗压委托的委托日期+配合比龄期<供应日期时 签发日期=供应日期+配合比龄期+1*/
                    dateNum = lq + 1;
                    rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(supplyStartTime, Calendar.DATE, dateNum, "yyyy-MM-dd"));
                }
            }
            /*else {
                if(rwdextraPrintInfo.getKsExperimentId() != null){
                    *//** 如果有抗渗 取抗渗报告日期 +1天  **//*
                    Experiment experiment = experimentMapper.loadById(rwdextraPrintInfo.getKsExperimentId());
                    if(experiment.getReportDate() != null){
                        rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(experiment.getReportDate(),Calendar.HOUR,24,"yyyy-MM-dd"));
                    }
                }

                if(!kyExperimentIdList.isEmpty()){
                    *//** 如果抗渗没有 取抗压报告 报告日期最大一条 报告日期+1天  **//*
                    Date entrustTime = experimentMapper.getMaxExperimentEntrustTime(kyExperimentIdList);
                    if(entrustTime != null){
                        rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(entrustTime,Calendar.HOUR,24,"yyyy-MM-dd"));
                    }
                }
            }*/
        }
        entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
        entity.setRwdextraPrintInfo(rwdextraPrintInfo);
        entity.setSupplyStartTime(NullUtils.ifNullDate(rwdextraPrintInfo.getCustomer().getSupplyStartTime()));
        entity.setSupplyEndTime(NullUtils.ifNullDate(rwdextraPrintInfo.getCustomer().getSupplyEndTime()));
        entity.setOpenAppraisalNo(rwdextraPrintInfo.getKpjdbh());
        entity.setQualityCertificateNo(rwdextraPrintInfo.getCchgzbh());
        return entity;
    }

    private void setRwdextraValue(RwdextraExtend rwdextraExtend, Rwdextra rwdextra) {
        rwdextraExtend.setRwdextraPrintInfo(JsonUtils.getObject(rwdextraExtend.getPrintJson(), RwdextraPrintInfo.class));
        /**如果修改过,需要重新复制到任务单中**/
        /** 计划方量 **/
        if (StringUtils.isNotBlank(rwdextraExtend.getPlanQuantity())) {
            rwdextra.getRwdextraInfo().setFJhsl(rwdextraExtend.getPlanQuantity());
        }
        /** 施工部位 **/
        if (StringUtils.isNotBlank(rwdextraExtend.getPouringPosition())) {
            rwdextra.getRwdextraInfo().setFJzbw(rwdextraExtend.getPouringPosition());
        }
        /** 配合比报告编号 **/
        if (StringUtils.isNotBlank(rwdextraExtend.getRwdextraPrintInfo().getPhbbgbh())) {
            rwdextra.getRwdextraInfo().setFRwno(rwdextraExtend.getRwdextraPrintInfo().getPhbbgbh());
        }
        RwdextraPrintInfo.Customer customer = rwdextraExtend.getRwdextraPrintInfo().getCustomer();
        if (customer != null) {
            /** 工程名称 **/
            if (StringUtils.isNotBlank(customer.getProjectName())) {
                rwdextra.getRwdextraInfo().setFGcmc(customer.getProjectName());
            }
            /** 施工单位 **/
            if (StringUtils.isNotBlank(customer.getCustomerName())) {
                rwdextra.setBuildNameNew(customer.getCustomerName());
                rwdextra.getRwdextraInfo().setFHtdw(customer.getCustomerName());
            }
            /** 供应数量 **/
            if (StringUtils.isNotBlank(rwdextraExtend.getRwdextraPrintInfo().getFWcsl())) {
                rwdextra.getRwdextraInfo().setFWcsl(rwdextraExtend.getRwdextraPrintInfo().getFWcsl());
            }
            /** 砼品种 **/
            if (StringUtils.isNotBlank(customer.getFtpz())) {
                rwdextra.getRwdextraInfo().setFTpz(customer.getFtpz());
                String ksdjOld = ConvertUtils.getMesTpzToKs(rwdextra.getRwdextraInfo().getFTbj());
                String ksdj = ConvertUtils.getMesTpzToKs(customer.getFtpz());
                rwdextra.getRwdextraInfo().setFTbj(rwdextra.getRwdextraInfo().getFTbj().replace(ksdjOld, ksdj));
            }
            /** 配合比号 **/
            if (StringUtils.isNotBlank(customer.getFPhbNo())) {
                rwdextra.getRwdextraInfo().setFPhbNo(customer.getFPhbNo());
                rwdextra.getRwdextraInfo().setPhbshow(customer.getFPhbNo());
                rwdextra.setPhbshow(customer.getFPhbNo());
            }
            /** 计划日期 **/
            if (StringUtils.isNotBlank(customer.getPlantimeStart())) {
                rwdextra.getRwdextraInfo().setFJhrq(customer.getPlantimeStart());
                rwdextra.setPlantime(DateHelper.parseDateList(customer.getPlantimeStart()));
            }
            /** 塌落度 **/
            if (StringUtils.isNotBlank(customer.getTld())) {
                rwdextra.getRwdextraInfo().setFTld(customer.getTld());
            }
            /** 完成方量 **/
            if (org.apache.commons.lang.StringUtils.isNotBlank(customer.getFhquantity())) {
                rwdextra.setFhquantity(Float.valueOf(customer.getFhquantity()));
            }
        }
    }

    @Override
    public Map<Integer, RwdextraExtend> getRwdextraExtendMap(Set<Integer> frwdList) {
        Map<Integer, RwdextraExtend> rwdextraExtendMap = new HashMap<>();
        if (frwdList.isEmpty()) {
            return rwdextraExtendMap;
        }
        List<RwdextraExtend> list = rwdextraExtendMapper.selectByFRwdhList(frwdList);
        for (RwdextraExtend rwdextraExtend : list) {
            rwdextraExtendMap.put(rwdextraExtend.getFrwdh(), rwdextraExtend);
        }
        return rwdextraExtendMap;
    }

    private void setRwdextraExtendPrintKs(Rwdextra rwdextra, RwdextraPrintInfo rwdextraPrintInfo, GenConcreteResult genConcreteResult) {
        if (genConcreteResult == null) {
            return;
        }
        if (StringUtils.isNotBlank(genConcreteResult.getKsExperimentId())) {
            Long ksExperimentId = Long.valueOf(genConcreteResult.getKsExperimentId());
            rwdextraPrintInfo.setKsExperimentId(ksExperimentId);
            Experiment experiment = experimentMapper.loadById(ksExperimentId);
            rwdextraPrintInfo.setKstzypbh(experiment.getSampleId());
            rwdextraPrintInfo.setKstzjl(NullUtils.isQualified(experiment.getIsQualified()));
            /**试验台账对应试验项目信息*/
            /*List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(ksExperimentId, TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode());
            if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                *//**将json转成对象*//*
                ConcreteKsdj concreteKsdj = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteKsdj.class);
                String ssksdj = concreteKsdj.getSsksdj();
                String ksdj = rwdextra.getRwdextraInfo().getFTbj().split("|")[3];
                if (StringUtils.isNotBlank(ksdj)) {
                    if (ssksdj.compareTo(ksdj) >= 0) {
                        rwdextraPrintInfo.setKstzjl("合格");
                    } else {
                        rwdextraPrintInfo.setKstzjl("不合格");
                    }
                } else {
                    rwdextraPrintInfo.setKstzjl("合格");
                }
            }*/
        }
        if (StringUtils.isNotBlank(genConcreteResult.getKyExperimentId())) {
            Long kyExperimentId = Long.valueOf(genConcreteResult.getKyExperimentId());
            rwdextraPrintInfo.setKyExperimentId(kyExperimentId);
        }
    }

    private void setRwdextraExtendPrintKy(RwdextraPrintInfo rwdextraPrintInfo, GenConcreteResult genConcreteResult) {
        if (genConcreteResult == null) {
            return;
        }
        if (StringUtils.isNotBlank(genConcreteResult.getKyExperimentId())) {
            Long experimentId = Long.valueOf(genConcreteResult.getKyExperimentId());
            List<String> kytzList;
            List<RwdextraPrintInfo.Kytz> kyInfoList;
            if (rwdextraPrintInfo.getKyInfoList() == null) {
                kytzList = new ArrayList<>();
                kyInfoList = new ArrayList<>();

            } else {
                kyInfoList = rwdextraPrintInfo.getKyInfoList();
                kytzList = rwdextraPrintInfo.getKytzList();
            }
            if (RwdextraPrintInfo.existsInArray(kyInfoList, genConcreteResult.getKyExperimentId())) {
                return;
            }
            RwdextraPrintInfo.Kytz kytz = new RwdextraPrintInfo.Kytz();
            Experiment experiment = experimentMapper.loadById(experimentId);
            if (experiment != null) {
                if (StringUtils.isNotBlank(experiment.getSampleId())) {
                    kytzList.add(experiment.getSampleId());
                } else {
                    kytzList.add(experiment.getExperimentNo());
                }
                kytz.setWtbh(experiment.getExperimentNo());
                kytz.setXhwtbh(experiment.getConsignId());
                kytz.setYpbh(experiment.getSampleId());
                kytz.setSytzbh(String.valueOf(experiment.getId()));
                List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_KYQD.getCode());
                if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                    /**将json转成对象*/
                    ConcreteKyqd concreteKyqd = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteKyqd.class);
                    kytz.setQdpjz(concreteKyqd.getPjz28d());
                    kytz.setDdsjqd(concreteKyqd.getFyxs28d());
                    kytz.setZsbzqd(concreteKyqd.getZsbzqd28d());
                }
                kyInfoList.add(kytz);
            }
            rwdextraPrintInfo.setKytzList(kytzList);
            rwdextraPrintInfo.setKyInfoList(kyInfoList);

            /* *//**塌落度对应实验项目赋值**//*
            List<ExperimentDetail> experimentDetailListTld = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_MCTLD.getCode());
            if (CollectionUtil.isNotEmpty(experimentDetailListTld)) {
                *//**将json转成对象*//*
                ConcreteMctld concreteMctld = experimentDetailListTld.get(0).getObjJson().toJavaObject(ConcreteMctld.class);
                rwdextraPrintInfo.setSctld(NullUtils.ifNull(concreteMctld.getTld1() + "±" + concreteMctld.getTld1()));
            }

            *//**粘聚性对应实验项目赋值**//*
            List<ExperimentDetail> experimentDetailListZjx = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_ZJX.getCode());
            if (CollectionUtil.isNotEmpty(experimentDetailListZjx)) {
                *//**将json转成对象*//*
                ConcreteZjx concreteZjx = experimentDetailListZjx.get(0).getObjJson().toJavaObject(ConcreteZjx.class);
                if ("1".equals(concreteZjx.getFcc())) {
                    rwdextraPrintInfo.setSczjx("非常差");
                } else if ("1".equals(concreteZjx.getYb())) {
                    rwdextraPrintInfo.setSczjx("一般");
                } else if ("1".equals(concreteZjx.getHh())) {
                    rwdextraPrintInfo.setSczjx("良好");
                }
            }

            *//**保水性对应实验项目赋值**//*
            List<ExperimentDetail> experimentDetailListBsx = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_BSX.getCode());
            if (CollectionUtil.isNotEmpty(experimentDetailListBsx)) {
                *//**将json转成对象*//*
                ConcreteBsx concreteBsx = experimentDetailListBsx.get(0).getObjJson().toJavaObject(ConcreteBsx.class);
                if ("1".equals(concreteBsx.getFcc())) {
                    rwdextraPrintInfo.setScbsx("非常差");
                } else if ("1".equals(concreteBsx.getYb())) {
                    rwdextraPrintInfo.setScbsx("一般");
                } else if ("1".equals(concreteBsx.getHh())) {
                    rwdextraPrintInfo.setScbsx("良好");
                }
            }*/
        }
    }

    private void setRwdextraExtendPrintKz(RwdextraPrintInfo rwdextraPrintInfo, GenConcreteResult genConcreteResult) {
        /**抗折**/
        if (StringUtils.isNotBlank(genConcreteResult.getKzExperimentId())) {
            Long experimentId = Long.valueOf(genConcreteResult.getKzExperimentId());
            rwdextraPrintInfo.setKzExperimentId(experimentId);
            Experiment experiment = experimentMapper.loadById(experimentId);
            if (experiment != null) {
                rwdextraPrintInfo.setKztzypbh(experiment.getSampleId());
                rwdextraPrintInfo.setKztzwtbh(experiment.getExperimentNo());
            }
            rwdextraPrintInfo.setKzExperimentId(experimentId);
        }
    }

    private void setRwdextraExtendPrintKllz(RwdextraPrintInfo rwdextraPrintInfo, GenConcreteResult genConcreteResult, String kllz) {
        /**抗氯离子**/
        if (StringUtils.isNotBlank(genConcreteResult.getKllExperimentId())) {
            Long experimentId = Long.valueOf(genConcreteResult.getKllExperimentId());
            rwdextraPrintInfo.setKllExperimentId(experimentId);
            Experiment experiment = experimentMapper.loadById(experimentId);
            rwdextraPrintInfo.setKllztzypbh(experiment.getSampleId());
            rwdextraPrintInfo.setKllztzwtbh(experiment.getExperimentNo());
        }
        if (StringUtils.isNotBlank(kllz)) {
            rwdextraPrintInfo.setLlzhl(kllz);
        }
    }

    @Override
    public void setMaterialsInfo(RwdextraExtendMaterials entity) {
        log.info("设置任务单原材料。对应入参：【{}】", JsonUtils.getJson(entity));
        Integer frwdh = entity.getFrwdh();
        if (frwdh == null) {
            return;
        }
        RwdextraExtend extendInfo = rwdextraExtendMapper.selectByFRwdh(frwdh);
        if (extendInfo == null) {
            extendInfo = new RwdextraExtend();
            extendInfo.setCreateTime(new Date());
            extendInfo.setUpdateTime(new Date());
            extendInfo.setFrwdh(frwdh);
            extendInfo.setBindMaterialsTime(new Date());
            extendInfo.setMaterialsInfoJson(JsonUtils.beanToObject(entity));
            rwdextraExtendMapper.insertSelective(extendInfo);
        } else {
            extendInfo.setUpdateTime(new Date());
            extendInfo.setMaterialsInfoJson(JsonUtils.beanToObject(entity));
            extendInfo.setBindMaterialsTime(new Date());
            rwdextraExtendMapper.updateByPrimaryKeySelective(extendInfo);
        }
    }

    @Override
    public RwdextraExtendMaterials getMaterialsInfo(RwdextraExtendMaterials entity) {
        log.info("获取任务单原材料。对应任务单：【{}】", entity.getFrwdh());
        RwdextraExtendMaterials rwdextraExtendMaterials = new RwdextraExtendMaterials();

        try {
            Integer frwdh = entity.getFrwdh();
            if (frwdh == null) {
                return rwdextraExtendMaterials;
            }
            rwdextraExtendMaterials.setFrwdh(frwdh);
            RwdextraExtend extendInfo = rwdextraExtendMapper.selectByFRwdh(frwdh);
            if (extendInfo == null) {
                return rwdextraExtendMaterials;
            }
            rwdextraExtendMaterials = JsonUtils.getObject(extendInfo.getMaterialsInfoJson(), RwdextraExtendMaterials.class);
            return rwdextraExtendMaterials;
        } catch (Exception e) {
            log.error("获取任务单原材料失败。对应任务单：【{}】", entity.getFrwdh(), e);
            return rwdextraExtendMaterials;
        }
    }

    @Override
    public void setRwdextraPrintInfoPhb(ErpAddTaskPhbLog erpAddTaskPhbLog) {
        String taskIds = erpAddTaskPhbLog.getTaskIds();
        String phbNo = erpAddTaskPhbLog.getPhbNo();
        if (StringUtils.isBlank(taskIds) || StringUtils.isBlank(phbNo)) {
            log.info("ERP上传配合比调整日志，缺少任务单ID或者配合比号，对应调整日志对象：【{}】", erpAddTaskPhbLog);
            return;
        }
        String[] taskIdArr = taskIds.split(",");
        MixProportion selectByPhbNo = mixProportionMapper.selectByPhbNo(phbNo);
        if (selectByPhbNo == null) {
            log.info("ERP上传配合比调整日志，不存在配合比信息：【{}】", phbNo);
            return;
        }
        JSONObject proportionMaterial = selectByPhbNo.getProportionMaterial();
        try {
            for (String taskId : taskIdArr) {
                Rwdextra rwdextra = rwdextraService.selectByFrwdh(Integer.valueOf(taskId));
                log.info("ERP上传配合比调整日志，开始绑定配合比信息：【{}】", JsonUtils.getJson(proportionMaterial));
                RwdextraExtend rwdextraExtend = rwdextra.getRwdextraExtend();
                if (rwdextraExtend != null) {
                    RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(rwdextraExtend.getPrintJson(), RwdextraPrintInfo.class);
                    selectByPhbNo.setProportionMaterial(JsonUtils.beanToObject(proportionMaterial));
                    rwdextraPrintInfo.setMixProportionInfo(selectByPhbNo);
                    rwdextraExtend.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
                    rwdextraExtendMapper.updateByPrimaryKeySelective(rwdextraExtend);
                }
            }
        } catch (Exception e) {
            log.error("ERP上传配合比调整日志，绑定配合比信息失败。对应任务单：【{}】", taskIdArr, e);
        }
    }
}
